import { breakpointsTailwind, useBreakpoints, useToggle } from '@vueuse/core'
import { getWebsiteConfig, listDictData } from '@/apis'
import type { LabelValue } from '@/types/global'

export const useAppStore = defineStore('app', () => {
  // 是否为移动端/桌面端
  const breakpoints = useBreakpoints(breakpointsTailwind)
  const isMobile = breakpoints.smaller('sm')
  const isDesktop = computed(() => !isMobile.value)
  const layout = ref('mix')
  const menuAccordion = ref(false)

  // 侧栏菜单是否折叠
  const [menuCollapsed, toggleMenuCollapsed] = useToggle(false)

  // 网站配置信息
  const website = ref<WebsiteConfig>({
    logo: '/logo.png',
    title: import.meta.env.VITE_APP_NAME,
    copyright: '',
    icp: '',
  })

  // 主题配置
  const theme = reactive<ThemeConfig>({
    mode: 'light',
    layout: 'mixed',
  })

  // 页面重新加载
  const reloadFlag = ref(true)
  const reloadPage = () => {
    reloadFlag.value = false
    nextTick(() => {
      reloadFlag.value = true
    })
  }

  /**
   * 初始化主题
   */
  const initTheme = () => {

  }

  /**
   * 初始化网站配置
   */
  const initWebsiteConfig = async () => {
    website.value = await getWebsiteConfig()
    document.querySelector('link[rel="shortcut icon"]')?.setAttribute('href', website.value.logo || '/logo.png')
  }

  /**
   * 字典数据
   */
  const dictList = ref<Record<string, LabelValue[]>>({})

  /**
   * 字典数据
   */
  const dictMap = computed(() => {
    const data = {}
    for (const key in dictList.value) {
      const dict = {}
      dictList.value[key].forEach(item => dict[item.value] = item)
      data[key] = dict
    }
    return data
  })

  /**
   * 初始化字典
   */
  const initDict = async () => {
    dictList.value = await listDictData()
  }

  return {
    layout,
    isMobile,
    isDesktop,
    menuCollapsed,
    menuAccordion,
    toggleMenuCollapsed,
    website,
    theme,
    dictList,
    dictMap,
    initTheme,
    initWebsiteConfig,
    reloadFlag,
    reloadPage,
    initDict,
  }
})
